package com.cj.utils;

import com.cj.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//@WebFilter("/*")
public class LoginFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
//            已经登陆了
            filterChain.doFilter(request,response);
        }else{
            String uri = request.getRequestURI();
            String method = request.getParameter("method");
            if (uri.contains("code") || "login".equals(method)  || "loginOut".equals(method) || "findUser".equals(method) ){
                filterChain.doFilter(request,response);
            }else{
                ResultVO vo = new ResultVO(401, "登录后再操作", null);
                JSONUtils.objToJson(vo,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
